<template>
  <div
    class="main"
    v-loading="loading"
    element-loading-text="解析中,请稍后"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-steps :active="active" finish-status="success">
      <el-step title="基本信息"></el-step>
      <el-step title="商品规格"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品详情"></el-step>
    </el-steps>
    <div class="content" v-show="show1">
      <el-form ref="form1" :model="form1" label-width="100px" :rules="rules">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form1.name" placeholder="输入商品名称" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="商品类目" prop="categoryId">
          <el-select v-model="form1.categoryId" placeholder="请选择">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品标签">
          <el-select v-model="form1.labelId" placeholder="请选择">
            <el-option v-for="item in labels" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品主图">
          <el-upload
            :action="action"
            :headers="header"
            list-type="picture"
            :limit="mainLimit"
            :on-exceed="exceed"
            :file-list="mainFileList"
            :on-success="uploadMainSuccess"
            :on-remove="removeMain"
          >
            <el-button type="primary" size="small">上传主图</el-button>
            <div slot="tip" class="el-upload__tip">只能上传图片文件，且不超过500k，最多一张</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播图">
          <el-upload
            :action="action"
            list-type="picture"
            :headers="header"
            :limit="bannerLimit"
            :on-exceed="exceed"
            :on-remove="removeBanner"
            :on-success="uploadBannerSuccess"
            multiple
            :file-list="bannerFileList"
          >
            <el-button type="primary" size="small">上传轮播图</el-button>
            <div slot="tip" class="el-upload__tip">只能上传图片文件，且不超过500kb，最多五张</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="foot">
        <el-button type="primary" size="small" @click="next('form1')">下一步</el-button>
      </div>
    </div>
    <div class="content" v-show="show2">
      <div>
        <div>
          <el-form>
            <el-form-item label="商品属性">
              <el-input v-model="attribute" placeholder="如 ：颜色 " style="width:400px" clearable></el-input>
              <el-button type="primary" size="small" style="margin:0 20px" @click="addAttribute">确定</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <label class="lable">商品规格</label>
        </div>
        <div class="attr_content">
          <div style="margin-top:30px" v-for="(item ,index) in attributes" :key="index">
            <div>
              <el-input v-model="item.attrName" placeholder="修改属性" style="width:100px" clearable></el-input>
              <el-popover placement="right" trigger="hover" :content="'添加'+item.attrName">
                <el-button
                  @click="addAttrValue(index)"
                  slot="reference"
                  type="text"
                  style="margin-left:10px;font-size:20px"
                >+</el-button>
              </el-popover>
              <el-popover placement="right" trigger="hover" :content="'删除整个'+item.attrName">
                <el-button
                  @click="reAttribute(index)"
                  slot="reference"
                  type="text"
                  style="margin-left:10px;font-size:20px;color:#FF0000"
                >-</el-button>
              </el-popover>
            </div>
            <div class="item_content">
              <div class="item" v-for="(attrValue,index2) in item.attrValues" :key="index2">
                <div class="item_head">
                  <el-button
                    type="text"
                    style="padding:5px;color:#FF0000"
                    @click="reAttrValue(index,index2)"
                  >x</el-button>
                </div>
                <div class="item_lable">
                  <span class="lable">属性值：</span>
                  <el-input
                    v-model="attrValue.attrValue"
                    placeholder="输入属性值"
                    style="width:200px"
                    size="small"
                  ></el-input>
                </div>
                <div style="margin-top:20px;width:100%;padding-right:20px">
                  <el-upload
                    :action="action"
                    list-type="picture"
                    :headers="header"
                    :limit="mainLimit"
                    :on-exceed="exceed"
                    :file-list="attrValue.pic"
                    :on-success="(response, file, fileList)=>uploadSuccessPic(response, file, fileList,index,index2)"
                    :on-remove="(file, fileList)=>removePic(file, fileList,index,index2)"
                  >
                    <el-button v-show="attrValue.pic.length==0" type="primary" size="small">上传规格图</el-button>
                  </el-upload>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div style="margin-top:30px">
        <div>
          <label class="lable">SKU列表</label>
          <el-button style="margin-left:10px" size="small" @click="refreshSKUList">刷新SKU列表</el-button>
        </div>
        <div style="margin-top:30px">
          <el-table border v-show="skuList.length!=0" :data="skuList">
            <el-table-column v-for="(item,i) in attributes" :key="i">
              <template slot="header" slot-scope="scope">
                <span>{{item.attrName}}</span>
              </template>
              <template slot-scope="scope">
                <span>{{scope.row.skuName[i].value}}</span>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot="header" slot-scope="scope">
                <span>价格</span>
                <el-button type="text" size="small" @click="refreshColumn('price')">
                  <i class="el-icon-refresh"></i>
                </el-button>
              </template>
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" placeholder="价格"></el-input>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot="header" slot-scope="scope">
                <span>原价</span>
                <el-button type="text" size="small" @click="refreshColumn('marketPrice')">
                  <i class="el-icon-refresh"></i>
                </el-button>
              </template>
              <template slot-scope="scope">
                <el-input v-model="scope.row.marketPrice" placeholder="原价"></el-input>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot="header" slot-scope="scope">
                <span>成本价</span>
                <el-button type="text" size="small" @click="refreshColumn('costPrice')">
                  <i class="el-icon-refresh"></i>
                </el-button>
              </template>
              <template slot-scope="scope">
                <el-input v-model="scope.row.costPrice" placeholder="成本价"></el-input>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot="header" slot-scope="scope">
                <span>库存</span>
                <el-button type="text" size="small" @click="refreshColumn('stock')">
                  <i class="el-icon-refresh"></i>
                </el-button>
              </template>
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock" placeholder="库存"></el-input>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot="header" slot-scope="scope">
                <span>销量</span>
                <el-button type="text" size="small" @click="refreshColumn('saleNum')">
                  <i class="el-icon-refresh"></i>
                </el-button>
              </template>
              <template slot-scope="scope">
                <el-input v-model="scope.row.saleNum" placeholder="销量"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="上下架">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="activeValue"
                  :inactive-value="inactiveValue"
                ></el-switch>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="foot">
        <el-button size="small" @click="prev('form2')">上一步</el-button>
        <el-button type="primary" size="small" @click="next('form2')">下一步</el-button>
      </div>
    </div>
    <div v-show="show3" class="content2 content">
      <div style="width:100%;display:flex;justify-content:flex-end">
        <el-button type="primary" size="small" @click="addParam">添加</el-button>
      </div>
      <div style="width:500px;margin-top:30px">
        <el-table :data="paramList" border>
          <el-table-column label="参数">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" placeholder="参数"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="参数值">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" placeholder="参数值"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="删除">
            <template slot-scope="scope">
              <el-button type="warning" size="small" @click="delParam(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="foot">
        <el-button size="small" @click="prev('form3')">上一步</el-button>
        <el-button type="primary" size="small" @click="next('form3')">下一步</el-button>
      </div>
    </div>
    <div v-show="show4" class="content">
      <TinymceEditor v-model="detail" :header="header" :action="action"></TinymceEditor>
      <div class="foot">
        <el-button size="small" @click="prev('form4')">上一步</el-button>
        <el-button size="small" type="primary" @click="submitProduct()">完成</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import TinymceEditor from "@/components/tinymce";
import { list } from "@/api/category.js";
import { add, detail, getCrawlDetail } from "@/api/product.js";
import label from "@/api/label.js";
import { getToken } from "@/utils/auth.js";
export default {
  components: {
    TinymceEditor
  },
  data() {
    return {
      loading: false,
      activeValue: 0,
      inactiveValue: 1,
      detail: "",
      paramList: [],
      mainLimit: 1,
      bannerLimit: 5,
      header: {},
      mainFileList: [],
      bannerFileList: [],
      action: "",
      show1: true,
      show2: false,
      show3: false,
      show4: false,
      active: 0,
      options: [],
      labels: [],
      props: {
        value: "id",
        label: "name",
        children: "categories",
        expandTrigger: ""
      },
      rules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        categoryId: [
          { required: true, message: "请选择商品类目", trigger: "change" }
        ]
      },
      form1: {
        name: "",
        categoryId: "",
        labelId: ""
      },
      attribute: "",
      attributes: [],
      skuList: [],
      editId: 0
    };
  },
  mounted() {
    this.editId = this.$route.query.id;
    this.form1.categoryId = this.$route.query.categoryId;
    if (this.$route.query.url != null) {
      this.loading = true;
      this.getCrawlDetail(this.$route.query.url);
    }
    if (this.editId != null) {
      this.getDetail(this.editId);
    }
    this.action = this.$UPLOAD;
    this.header = { token: getToken() };
    this.initCategory();
    this.initLabel();
  },
  methods: {
    //获取商品详情
    getCrawlDetail(url) {
      getCrawlDetail(url).then(res => {
        this.form1.name = res.data.productName;
        let banner = res.data.bannerImages;
        for (var i = 0; i < banner.length; i++) {
          let s = {
            name: this.getNameByUrl(banner[i]),
            url: banner[i]
          };
          this.bannerFileList.push(s);
        }

        this.mainFileList.push({
          name: this.getNameByUrl(res.data.mainImage),
          url: res.data.mainImage
        });

        this.detail = res.data.detail;

        //商品属性
        let attrs = res.data.attributes;
        for (var i = 0; i < attrs.length; i++) {
          let s = {
            attrName: "",
            attrValues: []
          };
          s.attrName = attrs[i].name;
          for (var j = 0; j < attrs[i].values.length; j++) {
            let value = {
              attrValue: "",
              pic: []
            };
            value.attrValue = attrs[i].values[j].value;
            if (
              attrs[i].values[j].image != null &&
              attrs[i].values[j].image.trim() != ""
            ) {
              value.pic.push({
                name: this.getNameByUrl(attrs[i].values[j].image),
                url: attrs[i].values[j].image
              });
            }

            s.attrValues.push(value);
          }
          this.attributes.push(s);
        }

        //商品参数
        this.paramList = res.data.params;

        this.loading = false;
      });
    },
    //根据链接获取图片名称
    getNameByUrl(url) {
      let index = url.lastIndexOf("/");
      return url.substring(index + 1);
    },

    //获取商品详情
    getDetail(id) {
      detail(id).then(res => {
        this.form1.name = res.data.product.name;
        let banner = res.data.product.bannerImage.split(",");
        for (var i = 0; i < banner.length; i++) {
          let s = {
            name: this.getNameByUrl(banner[i]),
            url: banner[i]
          };
          this.bannerFileList.push(s);
        }

        this.mainFileList.push({
          name: this.getNameByUrl(res.data.product.mainImage),
          url: res.data.product.mainImage
        });
        this.form1.categoryId = res.data.product.categoryId;
        this.detail = res.data.product.detail;
        this.form1.labelId = res.data.product.labelId;

        //商品属性
        let attrs = res.data.productAttributes;
        for (var i = 0; i < attrs.length; i++) {
          let s = {
            attrName: "",
            attrValues: []
          };
          s.attrName = attrs[i].name;
          for (var j = 0; j < attrs[i].values.length; j++) {
            let value = {
              attrValue: "",
              pic: []
            };
            value.attrValue = attrs[i].values[j].name;
            if (
              attrs[i].values[j].image != null &&
              attrs[i].values[j].image.trim() != ""
            ) {
              value.pic.push({
                name: this.getNameByUrl(attrs[i].values[j].image),
                url: attrs[i].values[j].image
              });
            }

            s.attrValues.push(value);
          }
          this.attributes.push(s);
        }

        //商品SKU
        this.skuList = res.data.productSkus;

        //商品参数
        res.data.params.map(s =>
          this.paramList.push({ name: s.param, value: s.value })
        );
      });
    },
    //刷新列
    refreshColumn(column) {
      this.skuList.map(s => (s[column] = this.skuList[0][column]));
    },
    //添加商品
    submitProduct() {
      let s = {
        product: {},
        params: [],
        productAttributes: [],
        productSkus: []
      };
      //基本参数
      s.product.id = this.editId;
      s.product.name = this.form1.name;
      s.product.bannerImage = this.joinPicList(this.bannerFileList);
      s.product.mainImage = this.joinPicList(this.mainFileList);
      s.product.categoryId = this.form1.categoryId;
      s.product.detail = this.detail;
      if (this.form1.labelId != "") {
        s.product.labelId = this.form1.labelId;
      }

      //参数
      this.paramList.map(i => s.params.push({ param: i.name, value: i.value }));
      //属性
      for (var i = 0; i < this.attributes.length; i++) {
        let n = {};
        n.name = this.attributes[i].attrName;
        n.values = [];
        for (var j = 0; j < this.attributes[i].attrValues.length; j++) {
          n.values.push({
            name: this.attributes[i].attrValues[j].attrValue,
            image: this.joinPicList(this.attributes[i].attrValues[j].pic)
          });
        }
        s.productAttributes.push(n);
      }
      //SKU
      s.productSkus = this.skuList;

      add(s).then(response => {
        this.$message({
          type: "success",
          message: response.message
        });
        this.$router.push({ path: "/product/list" });
      });
    },
    //拼接图片列表
    joinPicList(list) {
      let s = "";
      for (var i = 0; i < list.length; i++) {
        if (list[i].response != null) {
          s += list[i].response.data + ",";
        } else {
          s += list[i].url + ",";
        }
      }
      return s.substring(0, s.length - 1);
    },

    //删除参数
    delParam(index) {
      this.paramList.splice(index, 1);
    },
    //添加商品参数
    addParam() {
      this.paramList.push({
        name: "",
        value: ""
      });
    },
    //刷新SKU列表
    refreshSKUList() {
      this.skuList = [];
      this.combinationSku(this.skuList, this.attributes, new Array(), 0);
    },

    //排列组合规格
    combinationSku(skuArray, attrArray, temp, index) {
      if (index == attrArray.length) {
        let s = {
          marketPrice: 0.0,
          price: 0.0,
          costPrice: 0.0,
          saleNum: 0,
          stock: 0,
          status: 0,
          skuName: []
        };
        for (var i = 0; i < attrArray.length; i++) {
          let skuName = {
            name: attrArray[i].attrName,
            value: temp[i].attrValue
          };
          s.skuName.push(skuName);
        }
        skuArray.push(s);
        return;
      }

      for (var i = 0; i < attrArray[index].attrValues.length; i++) {
        temp[index] = attrArray[index].attrValues[i];
        this.combinationSku(skuArray, attrArray, temp, index + 1);
      }
    },

    //上传属性图片
    uploadSuccessPic(response, file, fileList, index1, index2) {
      if (response.code === 2000) {
        this.attributes[index1].attrValues[index2].pic = fileList;
      } else {
        this.$message({
          type: "warning",
          message: response.message
        });
      }
    },
    //移除属性图
    removePic(file, fileList, index1, index2) {
      this.attributes[index1].attrValues[index2].pic = fileList;
    },
    //移除属性值
    reAttrValue(index1, index2) {
      this.attributes[index1].attrValues.splice(index2, 1);
    },
    //添加属性值
    addAttrValue(index) {
      let s = {
        attrValue: "",
        pic: []
      };
      this.attributes[index].attrValues.push(s);
    },
    //移除属性
    reAttribute(index) {
      this.attributes.splice(index, 1);
    },
    //添加属性
    addAttribute() {
      if (this.attribute.trim().length > 0) {
        let s = {
          attrName: this.attribute,
          attrValues: []
        };
        this.attributes.push(s);
        this.attribute = "";
      } else {
        this.$message({
          type: "warning",
          message: "商品属性不能为空"
        });
      }
    },
    //上一步
    prev(form) {
      if (form == "form2") {
        this.show1 = true;
        this.show2 = false;
        this.show3 = false;
        this.show4 = false;
        this.active = 0;
      } else if (form == "form3") {
        this.show1 = false;
        this.show2 = true;
        this.show3 = false;
        this.show4 = false;
        this.active = 1;
      } else if (form == "form4") {
        this.show1 = false;
        this.show2 = false;
        this.show3 = true;
        this.show4 = false;
        this.active = 2;
      }
    },
    //下一步
    next(form) {
      if (form == "form1") {
        this.$refs[form].validate(valid => {
          if (valid) {
            console.log(this.mainFileList);
            console.log(this.bannerFileList);
            if (
              this.mainFileList.length == 1 &&
              this.bannerFileList.length >= 1
            ) {
              this.active = 1;
              this.show1 = false;
              this.show2 = true;
              this.show3 = false;
              this.show4 = false;
            } else {
              this.$message({
                type: "warning",
                message: "主图和轮播图不能为空"
              });
            }
          }
        });
      } else if (form == "form2") {
        if (this.skuList.length == 0) {
          this.$message({
            type: "warning",
            message: "商品SKU列表不能为空"
          });
          return;
        }
        this.active = 2;
        this.show1 = false;
        this.show2 = false;
        this.show3 = true;
        this.show4 = false;
      } else if (form == "form3") {
        this.active = 3;
        this.show1 = false;
        this.show2 = false;
        this.show3 = false;
        this.show4 = true;
      }
    },
    removeBanner(file, fileList) {
      this.bannerFileList = fileList;
    },
    uploadBannerSuccess(response, file, fileList) {
      if (response.code === 2000) {
        this.bannerFileList = fileList;
      } else {
        this.$message({
          type: "warning",
          message: response.message
        });
      }
    },
    removeMain(file, fileList) {
      this.mainFileList = fileList;
    },
    uploadMainSuccess(response, file, fileList) {
      if (response.code === 2000) {
        this.mainFileList = fileList;
      } else {
        this.$message({
          type: "warning",
          message: response.message
        });
      }
    },
    initLabel() {
      label().then(res => {
        this.labels = res.data;
      });
    },
    exceed() {
      this.$message({
        type: "warning",
        message: "超出限制"
      });
    },
    initCategory() {
      list().then(res => {
        this.options = res.data;
      });
    }
  }
};
</script>
<style scope>
.content2 {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.main {
  width: 1000px;
  margin: 0 auto;
}
.content {
  margin-top: 50px;
  background-color: #ffffff;
  padding: 30px 30px;
}
.foot {
  margin-top: 40px;
  display: flex;
  width: 100%;
  justify-content: flex-end;
}
.attrList {
  margin-left: 80px;
  display: flex;
  flex-direction: row;
  align-items: center;
}
.lable {
  font-size: 14px;
  color: #606266;
}
.item {
  width: 300px;
  border-radius: 5px;
  border: 1px solid #b0e0e6;
  margin-top: 20px;
  margin-left: 30px;
  padding-left: 20px;
  padding-bottom: 20px;
}
.item_lable {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.item_head {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
.item_content {
  margin-left: 62px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.attr_content {
  margin-left: 30px;
}
</style>


